package com.useeinfo.asg.open.dashboard.security;

import com.useeinfo.asg.common.utils.CommUtil;
import com.useeinfo.asg.modules.logging.biz.AddressBiz;
import com.useeinfo.asg.modules.logging.biz.ResourceBiz;
import com.useeinfo.asg.modules.logging.entity.Address;
import com.useeinfo.asg.modules.logging.entity.Resource;
import com.useeinfo.asg.modules.security.biz.SystemRoleBiz;
import com.useeinfo.asg.modules.security.biz.SystemUserBiz;
import com.useeinfo.asg.modules.security.entity.SystemRole;
import com.useeinfo.asg.modules.security.entity.SystemUser;
import com.useeinfo.framework.extend.action.BaseAction;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/web/admin/systemUser")
public class SystemUserAction extends BaseAction {

    //private final static Logger logger = LoggerFactory.getLogger(SystemUserAction.class);
    private final static Integer DEFAULT_PAGE_LIST_NUM = 20;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private SystemRoleBiz systemRoleBiz;

    @Autowired
    private AddressBiz addressBiz;


    @Autowired
    private ResourceBiz resourceBiz;

    // ******************************************************************************
    // ******************************* 代码自动生成开始 *******************************
    // ******************************************************************************

    /**
     * 打开列表页面
     */
    @RequestMapping("/getSystemUserListPage")
    public ModelAndView getSystemUserListPage() {

        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("security/systemUser/systemUserList");
        modelAndView.setViewName("system/systemUser/list");

        return modelAndView;
    }

    /**
     * 分页获取JSON数据
     */
    @RequestMapping("/getSystemUserListJSON")
    @ResponseBody
    public JSONObject getSystemUserListJSON(@RequestParam(value = "page", required = false) String pageNowParam,
                                            @RequestParam(value = "rows", required = false) String pageSizeParam,
                                            @RequestParam(value = "userName", required = false) String userName,
                                            @RequestParam(value = "userAccount", required = false) String userAccount) {

        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);

        Map<String, String> sqlMap = new HashMap<String, String>();
        if (!CommUtil.null2String(userName).equals("")) {
            sqlMap.put("userName", CommUtil.null2String(userName));
        }
        if (!CommUtil.null2String(userAccount).equals("")) {
            sqlMap.put("userAccount", CommUtil.null2String(userAccount));
        }
        queryParam.setSqlMap(sqlMap);
        JSONObject jsonObject = systemUserBiz.findJSONList(queryParam);
        jsonObject.put("total", jsonObject.get("records"));
        return jsonObject;
    }

    /**
     * 获取详情页面
     */
    @RequestMapping("/getSystemUserViewPage")
    public ModelAndView getSystemUserViewPage(@RequestParam(value = "userId", required = false) String userIdParam) {

        Long userId = StringConverters.ToLong(userIdParam);

        SystemUser systemUser = null;
        if (userId != null) {
            systemUser = systemUserBiz.findModel(userId);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("security/systemUser/systemUserViewPart");
        modelAndView.addObject("systemUser", systemUser);
        return modelAndView;
    }

    /**
     * 获取编辑页面
     */
    @RequestMapping("/getSystemUserEditPage")
    public ModelAndView getSystemUserEditPage(@RequestParam(value = "isPage", required = false) String isPageParam,
                                              @RequestParam(value = "userId", required = false) String userIdParam,
                                              String industryId) {

        Long userId = StringConverters.ToLong(userIdParam);

        SystemUser systemUser = null;
        if (userId != null) {
            systemUser = systemUserBiz.findModel(userId);
        }
        if (systemUser == null && "1".equals(isPageParam)) {
            systemUser = systemUserBiz.getByUserAccount(userIdParam);
        }

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("level", "2");
        List<Address> addressList = addressBiz.findList(queryParam);

        List<SystemRole> roleList = systemRoleBiz.findList();
//
        ModelAndView modelAndView = new ModelAndView();
        if (null != systemUser) {
            Address address = systemUser.getAddress();
            if (null != address && address.getLevel() == 4) {
                modelAndView.addObject("addressName", address.getParent().getParent().getAddrName() +
                        address.getParent().getAddrName() + address.getAddrName());
            } else if (null != address && address.getLevel() == 3) {
                modelAndView.addObject("addressName",
                        address.getParent().getAddrName() + address.getAddrName());
            } else if (null != address && address.getLevel() == 2) {
                modelAndView.addObject("addressName", address.getAddrName());
            }

        }
        modelAndView.setViewName("security/systemUser/systemUserEditPart");
        modelAndView.addObject("systemUser", systemUser);
        modelAndView.addObject("roleList", roleList);
//		modelAndView.addObject("otherIndustry", otherIndustry);
        modelAndView.addObject("citys", addressList);
        modelAndView.addObject("isPage", isPageParam);
        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping(value = "/executeSystemUserEdit", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String executeSystemUserEdit(SystemUser systemUser, String systemRoleid, String address_id, String industr, MultipartFile nikeFile, String department) {
/*
        if (systemUser.getSystemRole() != null && systemUser.getSystemRole().getRoleId() == null) {
			systemUser.setSystemRole(null);
		}*/

        if (!CommUtil.null2String(systemRoleid).equals("")) {
            String[] ids = systemRoleid.split(",");
            Set set = new HashSet<>();
            for (String id : ids) {
                set.add(systemRoleBiz.findModel(CommUtil.null2Long(id)));
            }
            systemUser.setSystemRoleSet(set);
        }
        if (CommUtil.null2Long(address_id) > 0) {
            systemUser.setAddress(addressBiz.findModel(CommUtil.null2Long(address_id)));
        }
        // 部门
        if (!CommUtil.null2String(department).equals("")) {
            String[] departments = department.split(",");
            if (departments.length == 2) {
                systemUser.setDepartmentMark(3);
            } else {
                systemUser.setDepartmentMark(CommUtil.null2Int(departments[0]));
            }
        }
        //判断用户名是否重复
        if (systemUserBiz.existUserAccount(systemUser)) {
            return "您输入的用户名为空或已存在，请重新输入";
        }

        if (nikeFile != null && CommUtil.isImgFile(nikeFile.getContentType())) {
            String path = FileUtils.fileUpload(nikeFile, "userNike", "nike_pic");
            Resource resource = null;
            if (null != systemUser.getId())
                systemUser = systemUserBiz.findModel(systemUser.getId());
            if (null != systemUser.getResource()) {
                resource = systemUser.getResource();
            } else {
                resource = new Resource();
                resource.setCreateTime(new Date());
            }
            resource.setResType(6);
            resource.setResPath(path);
            resource.setResName("用户头像");
            resourceBiz.addOrUpdate(resource);
            systemUser.setResource(resource);
        }
        systemUserBiz.addOrUpdate(systemUser);
        return "1";
    }

    /**
     * 逻辑删除机构用户信息
     */
    @RequestMapping("/logicRemoveSystemUser")
    @ResponseBody
    public String logicRemoveSystemUser(@RequestParam(value = "userId", required = false) String userIdParam,
                                        @RequestParam(value = "isFakeDelete", required = false) String isFakeDelete) {

        Long userId = StringConverters.ToLong(userIdParam);

        if (isFakeDelete.equals("1")) {

            systemUserBiz.delete(userId);
        } else {
            systemUserBiz.deleteId(userId);
        }

        return "1";
    }

    // ******************************************************************************
    // ******************************* 代码自动生成结束 *******************************
    // ******************************************************************************
}